var checkLength=/([\u4E00-\u9FA5\uf900-\ufa2d])/g;
var checkPhone=/^((\(\d{2,3}\))|(\d{3}\-))?(13\d{9}|15\d{9}|17\d{9}|18\d{9})$/;
var editAdminInfo,roleGrid;
var pageObj1={type:"1100",width:[180],height:[0,0,0],htmlObj:["detail_div"]};
var layoutContainer1 = create_layout(pageObj1);
var roleToolbar;
var randomNum = getRandomNum();
var oldUserType;


$(function(){
	roleToolbar = layoutContainer1.layout.items[0].attachToolbar({});
	roleToolbar.setIconsPath(basePP + "images/main/button/toolbar/");
	roleToolbar.addInput("searchKey",3,"输入角色名",100);
	roleToolbar.addButton("search", 4, "查询", "viewStock.png", "");
	roleToolbar.setAlign("right");
	roleToolbar.attachEvent("onClick", doOnClickRoleTool);
	//增加搜索键盘事件
	initRoleGrid();
	searchRole();
	roleToolbar.attachEvent("onEnter", function(id, value){
		searchRole();
	});
	//----------------------------------------------------------------!!!样式!!!
	$('.inp').focus(function(){	this.value='';}); //获取焦点后置空输入框
	layoutContainer1.layout.items[0].fixSize(true, false);//固定布局尺寸
	$('.dhtmlxLayoutPolySplitterVerInactive div').css("width","3px");//分割线
});
function initRoleGrid() {
	roleGrid = layoutContainer1.grid[0];
	dmjplugs.grid.createGrid({
		  sm:'ch',
		  skin:'dhx_skyblue',
		  srcc:true,
		  validate : true,
		  columns:[ {header:'id',id:'roleId',width:10,hidden:true},
			       	{header:'角色名',id:'name',width:'*'}		    	
			      ]		       
	},roleGrid);
	roleGrid.setTotal(0);
	roleGrid.enableEditEvents(false,false,false);
	roleGrid.attachEvent("onRowSelect",onSelectRoleRow);
	roleGrid.setColumnHidden(0,true);
}
//初始化Form1
function doOnFormInit1(){
	//按钮事件
	if (typeof(editForm1) == "object"){
		editForm1.attachEvent("onButtonClick", function(name, command) {
			switch(command) {
				case 'save':doSave();break;
				case 'cancle':doCancle();break;
			}
		});
	}
	editForm1.setItemValue("userNametag","账号8-20位字母数字组合");
	editForm1.setItemValue("passwordtag","密码10-20位大小写字母数字组合");

	//校验事件
	$("input[name='realName']").focus(function () {
		$("input[name='realNametag']").css({color:"#666666"});
		editForm1.setItemValue("realNametag","0~20位字符");
	});
	$("input[name='realName']").blur(function () {
		var realName=$.trim($(this).val());
		var realName_lng=realName.replace(checkLength,'**').length;
		editForm1.setItemValue("realNametag","");
		$("input[name='realNametag']").css({color:"red"});
		if(realName.length==0){
			editForm1.setItemValue("realNametag","请填写姓名");
		}else if(realName_lng>20){
			editForm1.setItemValue("realNametag","0~20位字符 ");
		}
	});
	$("input[name='userName']").focus(function () {
		$("input[name='userNametag']").css({color:"#666666"});
		editForm1.setItemValue("userNametag","账号8-20位字母数字组合");
	});
	$("input[name='userName']").blur(function () {
		var userName=$.trim($(this).val());
		var userName_lng=userName.replace(checkLength,'**').length;
		editForm1.setItemValue("userNametag","");
		$("input[name='userNametag']").css({color:"red"});
		if(userName.length==0){
			editForm1.setItemValue("userNametag","请填写登录账号");
		}else if(userName_lng<8||userName_lng>20){
			editForm1.setItemValue("userNametag","账号8-20位字母数字组合");
    	}
	});
	$("input[name='password']").focus(function () {
		$("input[name='passwordtag']").css({color:"#666666"});
		editForm1.setItemValue("passwordtag","密码10-20位大小写字母数字组合");
	});
	$("input[name='password']").blur(function () {
		var password=$.trim($(this).val());
		var password_lng=password.length;
		editForm1.setItemValue("passwordtag","");
		$("input[name='passwordtag']").css({color:"red"});
		if(password.length==0){
			editForm1.setItemValue("passwordtag","请输入登录密码");
		}else if(password_lng<10||password_lng>20){
			editForm1.setItemValue("passwordtag","密码10-20位大小写字母数字组合");
		}
	});
	$("input[name='password']").on("paste",function(){
		return false;
	});
	$("input[name='password']").on("drop",function(){
		return false;
	});
	$("input[name='password']").on("contextmenu",function(){
		return false;
	});
	$("input[name='confirm_password']").on("paste",function(){
		return false;
	});
	$("input[name='confirm_password']").on("drop",function(){
		return false;
	});
	$("input[name='confirm_password']").on("contextmenu",function(){
		return false;
	});
	$("input[name='confirm_password']").focus(function () {
		$("input[name='confirm_passwordtag']").css({color:"#666666"});
		editForm1.setItemValue("confirm_passwordtag","密码10-20位大小写字母数字组合");
	});
	$("input[name='confirm_password']").blur(function () {
		var password=$.trim(editForm1.getItemValue("password"));
		var rePassword=$.trim($(this).val());
		var rePassword_lng=password.length;
		editForm1.setItemValue("confirm_passwordtag","");
		$("input[name='confirm_passwordtag']").css({color:"red"});
		if(rePassword_lng.length==0){
			editForm1.setItemValue("confirm_passwordtag","请输入确认密码");
		}else if(rePassword_lng<10||rePassword_lng>20){
			editForm1.setItemValue("confirm_passwordtag","密码10-20位大小写字母数字组合");
		}else if(password!=rePassword){
			editForm1.setItemValue("confirm_passwordtag","两次输入密码不一致");
		}
	});
	$("input[name='telephone']").blur(function () {
		var telephone=$.trim($(this).val());
		editForm1.setItemValue("telephonetag","");
		$("input[name='telephonetag']").css({color:"red"});
		if(telephone.length>0&&(telephone.length!=11||!checkPhone.exec(telephone))){
			editForm1.setItemValue("telephonetag","11位有效的手机号码");
		}
	});
	$("input[name='email']").blur(function () {
		var email=$.trim($(this).val());
		editForm1.setItemValue("emailtag","");
		$("input[name='emailtag']").css({color:"red"});
		if( email && email.length>0 && !email.isEmail() ){
			editForm1.setItemValue("emailtag","请输入有效的邮箱");
		}
	});
	//编辑窗口，修改密码校验，字段变成了modifyPassword，modifyPasswordtag，
	$("input[name='modifyPassword']").focus(function () {
		$("input[name='modifyPasswordtag']").css({color:"#666666"});
		editForm1.setItemValue("modifyPasswordtag","密码10-20位大小写字母数字组合");
	});
	$("input[name='modifyPassword']").blur(function () {
		var modifyPassword=$.trim($(this).val());
		var password_lng=modifyPassword.length;
		editForm1.setItemValue("modifyPasswordtag","");
		$("input[name='modifyPasswordtag']").css({color:"red"});
		if(modifyPassword.length==0){
			editForm1.setItemValue("modifyPasswordtag","请输入登录密码");
		}else if(password_lng<6||password_lng>20){
			editForm1.setItemValue("modifyPasswordtag","密码10-20位大小写字母数字组合");
		}
	});
	$("input[name='confirm_modifyPassword']").focus(function () {
		$("input[name='confirm_modifyPasswordtag']").css({color:"#666666"});
		editForm1.setItemValue("confirm_modifyPasswordtag","密码10-20位大小写字母数字组合");
	});
	$("input[name='confirm_modifyPassword']").blur(function () {
		var modifyPassword=$.trim(editForm1.getItemValue("modifyPassword"));
		var rePassword=$.trim($(this).val());
		var rePassword_lng=modifyPassword.length;
		editForm1.setItemValue("confirm_modifyPasswordtag","");
		$("input[name='confirm_modifyPasswordtag']").css({color:"red"});
		if(rePassword_lng.length==0){
			editForm1.setItemValue("confirm_modifyPasswordtag","请输入确认密码");
		}else if(rePassword_lng<6||rePassword_lng>20){
			editForm1.setItemValue("confirm_modifyPasswordtag","密码10-20位大小写字母数字组合");
		}else if(modifyPassword!=rePassword){
			editForm1.setItemValue("confirm_modifyPasswordtag","两次输入密码不一致");
		}
	});
	$("input[name='modifyPassword']").on("paste",function(){
		return false;
	});
	$("input[name='modifyPassword']").on("drop",function(){
		return false;
	});
	$("input[name='modifyPassword']").on("contextmenu",function(){
		return false;
	});
	$("input[name='confirm_modifyPassword']").on("paste",function(){
		return false;
	});
	$("input[name='confirm_modifyPassword']").on("drop",function(){
		return false;
	});
	$("input[name='confirm_modifyPassword']").on("contextmenu",function(){
		return false;
	});
	editForm1.disableItem("userTypetag");
	editForm1.disableItem("statustag");
	editForm1.disableItem("emailtag");
	editForm1.disableItem("realNametag");
	editForm1.disableItem("userNametag");
	editForm1.disableItem("passwordtag");
	editForm1.disableItem("userTypetag");
	editForm1.disableItem("confirm_passwordtag");
	editForm1.disableItem("telephonetag");
	editForm1.disableItem("modifyPasswordtag");
	editForm1.disableItem("confirm_modifyPasswordtag");

	var userTypeCombo=editForm1.getCombo('userType');
	userTypeCombo.addOption(parent.roleTypeComboData);
	userTypeCombo.setComboValue('admin');
	userTypeCombo.readonly(true);
	userTypeCombo.attachEvent("onChange",setRoleType);

	if(type=='edit') doOnForm1EditInit();
	if (type=='add') doOnForm1AddInit();
}

function setRoleType() {
	var userType_combo=editForm1.getCombo('userType');
	var userType = userType_combo.getSelectedValue();
	// if (oldUserType == 'sysadmin') {
		var roles =  getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
		if (roles != null && roles.length > 0) {
			editForm1.setItemValue("roleId",roles[0].roleId);
			editForm1.setItemValue("roleName",roles[0].name);
		} else {
			editForm1.setItemValue("roleId",null);
			editForm1.setItemValue("roleName","");
		}
	// }
	// if (userType == 'sysadmin') {
	// 	editForm1.setItemValue("roleName","系统管理员");
	// 	editForm1._disableItem("roleName");
	// }
	oldUserType = userType;
}

function doOnForm1AddInit() {
	 editForm1.hideItem("modifyPassword");
	 editForm1.hideItem("modifyPasswordtag");
	 editForm1.hideItem("userTypetag");
	 editForm1.hideItem("confirm_modifyPassword");
	 editForm1.hideItem("confirm_modifyPasswordtag");
	if(type=='add'){
		checkParam(randomNum);
	}
}
//完善编辑用户详情
function doOnForm1EditInit(){
	editForm1.setReadonly("userName",true);
	editForm1.hideItem("password");
	editForm1.hideItem("passwordtag");
	editForm1.hideItem("confirm_password");
	editForm1.hideItem("confirm_passwordtag");
	if (!id||id<=0)	return;

	var userType = editForm1.getCombo('userType');
	userType.setComboValue(parent.oneAdminInfo.userType);

	editForm1.setItemValue("id",escape2Html(parent.oneAdminInfo.id));
	editForm1.setItemValue("realName",escape2Html(parent.oneAdminInfo.realName));
	editForm1.setItemValue("userName",escape2Html(parent.oneAdminInfo.userName));
	editForm1.setItemValue("telephone",escape2Html(parent.oneAdminInfo.telephone));
	editForm1.setItemValue("email",escape2Html(parent.oneAdminInfo.email));

	$.ajax({
	    url: basePath+'managerUser/oneAdminInfo/'+id,
	    type: 'get',
	    dataType: 'json',
	   // data:postData,
	    success: function (back, textStatus, xhr) {
	    	if(!back){
	    		$func.alert("请求失败,状态:"+textStatus);
	    		return;
	    	}
	    	if(!back.result){
	    		$func.alert(back.message?back.message:"请求失败", "red");

	    		return;
	    	}
	    	if(!back.content) return;
	    	editAdminInfo=back.content;
	    	editForm1.setItemValue("roleId",editAdminInfo.roleId);
	    	editForm1.setItemValue("roleName",escape2Html(editAdminInfo.roleName));
			//左侧角色与右侧管理员管理角色关联起来，标记为选中状态
	        roleGrid.forEachRow(function (id) {
				var leftRowRoleName = $.trim(roleGrid.cells(id,roleGrid.getColIndexById('name')).getValue());
				var rightRoleName = editForm1.getInput("roleName").value;
				if (leftRowRoleName && leftRowRoleName.length>0 && leftRowRoleName == rightRoleName) {
					var rowIndex=roleGrid.getRowIndex(id);
						roleGrid.selectRow(rowIndex,true);
						return;
				}
			});
			// if (parent.oneAdminInfo.userType == 'sysadmin') {
			// 	editForm1.setItemValue("roleName", "系统管理员");
			// }
		},
		error:function (xhr, textStatus, errorThrown) {
			$func.alert("请求失败", "red");
		}
	});
}
//初始化按钮form
function doOnButtonForm(){
	if (typeof(buttonForm) == "object"){
		buttonForm.attachEvent("onButtonClick", function(name, command) {
			switch(command) {
				case 'save':doSave();break;
				case 'cancle':doCancle();break;
			}
		});
	}
}
//校验新增/编辑form表单
function checkForm(){
	$("input[name$='tag']").val("");
	var realName=$.trim(editForm1.getItemValue("realName"));
 	var userName=$.trim(editForm1.getItemValue("userName"));
	var password=$.trim(editForm1.getItemValue("password"));
	var repassword=$.trim(editForm1.getItemValue("confirm_password"));
	var telephone=$.trim(editForm1.getItemValue("telephone"));
	var roleId=$("input[name='roleId']:checked").val();
	var realName_lng=realName.replace(checkLength,'**').length;
	var userName_lng=userName.replace(checkLength,'**').length;
	var email=$.trim(editForm1.getItemValue("email"));
 	var roleId=$.trim(editForm1.getItemValue("roleId"));
 	var userType=$.trim(editForm1.getItemValue("userType"));

	if(type=='add'&&userName.length==0){
		$func.alert('请填写登录账号！', 'red');
		return false;
	}
	if(type=='add'&&password.length==0){
		$func.alert('请输入登录密码！', 'red');
		return false;
	}
	if(type=='add'&&repassword.length==0){
		$func.alert('请输入确认密码！', 'red');
		return false;
	}
	if(realName.length==0){
		$func.alert('请填写姓名！', 'red');
		return false;
	}
	var roleNameCheck = editForm1.getInput('roleName').value;
	if(!roleNameCheck){
		$func.alert("请点击左边栏选择角色值", "red");
		return;
	}
	var branchHoss = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
	if(!branchHoss){
		$func.alert("请选择一个角色", "red");
		return;
	}

	if(type=='add'&&!userName.isUserName()){
		$func.alert('登录账号必须是字母与数字组合', 'red');
		return false;
	}

	if(type=='add'&&(userName_lng<8||userName_lng>20)){
		$func.alert('登录账号必须8-20位字符', 'red');
		return false;
	}

	if(type=='add'&&(password.length<10||password.length>20)){
		$func.alert('登录密码长度:10-20位', 'red');
		return false;
	}
 	if(type=='add'&&!password.isPwd2()){
		$func.alert('登录密码必须是大小写字母和数字', 'red');
		return false;
	}
	if(type=='add'&&repassword.length==0){
		$func.alert('请输入确认密码！', 'red');
		return false;
	}

	if(type=='add'&&password!=repassword){
		$func.alert('两次输入密码不一致，请重输！', 'red');
		return false;
	}
	if(email&&!email.isEmail()){
		$func.alert('邮箱格式不正确！', 'red');
		return false;
	}
	if(realName_lng>20){
		$func.alert('姓名必须在20字符以内', 'red');
		return false;
	}
	if(telephone.length>0&&(telephone.length!=11||!checkPhone.exec(telephone))){
		$func.alert('联系手机格式不正确，请重填！', 'red');
		return false;
	}
	if(branchHoss.length !=1){
		$func.alert("只能勾选一个角色", "red");
		return;
	}
	//编辑窗口时，密码的修改校验
	var modifyPassword=$.trim(editForm1.getItemValue("modifyPassword"));
	var reModifyPassword=$.trim(editForm1.getItemValue("confirm_modifyPassword"));
	if(type=='edit'&& (modifyPassword.length>0||reModifyPassword.length>0)) {
		if ( modifyPassword.length == 0) {
			$func.alert('请输入修改密码！', 'red');
			return false;
		}
		if ( reModifyPassword.length == 0) {
			$func.alert('请输入确认密码！', 'red');
			return false;
		}
		if ( (modifyPassword.length < 10 || modifyPassword.length > 20)) {
			$func.alert('密码必须10~20位大小写字母和数字组合', 'red');
			return false;
		}

		if ( !modifyPassword.isPwd2()) {
			$func.alert('密码必须10~20位大小写字母和数字组合', 'red');
			return false;
		}
		if ( modifyPassword != reModifyPassword) {
			$func.alert('两次输入密码不一致，请重输！', 'red');
			return false;
		}
	}
	return true;
}
//保存动作
function doSave(){
	if(!checkForm())return;
	var formData = editForm1.getFormData();
	var postData="userName="+formData.userName;
	postData+="&status=enabled"+"&email="+(formData.email&&formData.email.length>0?formData.email:"");
	postData+="&telephone="+(formData.telephone&&formData.telephone.length>0?formData.telephone:"");
	postData+="&realName="+(formData.realName&&formData.realName.length>0?formData.realName:"");
	postData+="&roleId="+formData.roleId;
	postData+="&userType="+formData.userType;
	if (formData.modifyPassword.length>0){
		postData+="&password="+ $.md5(formData.confirm_modifyPassword).toUpperCase();
	}
	if(type=='add' ){
		postData+="&randomNum="+randomNum;
	}
	if(type=='edit') postData+="&id="+formData.id;
	if(type=='add') postData+="&password="+ $.md5(formData.confirm_password).toUpperCase();
	
	postData=encodeURI(postData);
	$.ajax({
        url: basePath+'managerUser/saveManagerUser',
        type: 'post',
        dataType: 'json',
        data:postData,
        success: function (back) {
        	if(!back||!back.result){
        		$func.alert(back.message?back.message:"保存失败", "red");
        		return;
        	}
        	$func.alert("保存成功！", "green");
        	parent.findPageGrid();
        	doCancle();
        }
    });
}
//取消动作
function doCancle(){
	parent.addAdminWin.close();
}

function doOnClickRoleTool(id){
	switch (id) {
		case 'search':searchRole();break;
	}
}
function searchRole(vContent){//加载疾病知识信息数据 ,先索引后数据库
	
	var searchType=1; //search_Form.getItemValue("docSearchType") ;
	var searchKey=roleToolbar.getValue("searchKey"); //search_Form.getItemValue("docSearchKey") ;
	if(vContent) searchKey=vContent;
	if(searchKey=='输入角色名') searchKey='';
	if(!searchKey||searchKey.length==0){
		/*	$func.alert("请填写“角色名”进行查询", "red");
		return;*/
	}
	roleGrid.setTotal(0);
	roleGrid.clearAll();
	var postData="pageNo=1&pageSize=200&pageCount=0";
	if(searchKey&&searchKey.length>0){
		postData+="&roleName="+searchKey;
	}
	postData+="&status=enabled";
  	$.ajax({
        url: basePath+'manageRole/findPageData', 
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
		success: function(back, textStatus, jqXHR) { 
	    	if(!back){
	    		$func.alert("请求失败,状态:"+textStatus);
	    		return;
	    	}
            if(back.rowCount>0){
            	roleGrid.parse(back.gridr, "json");
	           	roleGrid.setTotal(back.rowCount);
				roleGrid.uncheckAll();
				$("input[type='checkbox']").removeAttr('checked');
            }
        },
		error:function (xhr, textStatus, statustText) {
			$func.alert("请求失败,状态:"+textStatus , "red");
		}
    });
}
function onSelectRoleRow(rowID, celInd) {
	var  roleId=roleGrid.cells(rowID, roleGrid.getColIndexById('roleId')).getValue();
	var  name=roleGrid.cells(rowID, roleGrid.getColIndexById('name')).getValue();

	var userType = editForm1.getItemValue("userType");
	// if (userType != 'sysadmin') {
		editForm1.setItemValue("roleId",roleId);
		editForm1.setItemValue("roleName",name);
	// }
}